package com.agile4j.oss.adapter.impl;

import cn.hutool.core.lang.Assert;
import com.agile4j.oss.adapter.OssClientAdapter;
import com.agile4j.oss.core.OssProperties;
import com.cs.gzhn.ulid.UlidBuilder;
import com.google.common.collect.Iterables;
import io.minio.*;
import io.minio.errors.*;
import io.minio.http.Method;
import io.minio.messages.DeleteError;
import io.minio.messages.DeleteObject;
import io.minio.messages.Item;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.jetbrains.annotations.NotNull;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.stereotype.Component;
import org.springframework.util.DigestUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.net.URLEncoder;
import java.nio.channels.FileChannel;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.time.LocalDateTime;
import java.util.*;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

// MinioClientAdapter.java
@Component
@ConditionalOnProperty(name = "oss.type", havingValue = "minio")
public class MinioClientAdapter implements OssClientAdapter {

    @Autowired
    private MinioClient minioClient;

    @Autowired
    private OssProperties ossProperties;

    private static final Logger log = LoggerFactory.getLogger(MinioClientAdapter.class);
    final String PATH_SEPARATOR = "/";

    /**
     * description: 判断bucket是否存在，不存在则创建
     *
     * @return: void
     */
    @Override
    public void existBucket(String name) {
        try {
            boolean exists = minioClient.bucketExists(BucketExistsArgs.builder().bucket(name).build());
            if (!exists) {
                minioClient.makeBucket(MakeBucketArgs.builder().bucket(name).build());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 创建存储bucket
     *
     * @param bucketName 存储bucket名称
     * @return Boolean
     */
    @Override
    public Boolean makeBucket(String bucketName) {
        try {
            minioClient.makeBucket(MakeBucketArgs.builder()
                    .bucket(bucketName)
                    .build());
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    /**
     * 删除存储bucket
     *
     * @param bucketName 存储bucket名称
     * @return Boolean
     */
    @Override
    public Boolean removeBucket(String bucketName) {
        try {
            minioClient.removeBucket(RemoveBucketArgs.builder()
                    .bucket(bucketName)
                    .build());
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }


    /**
     * description: 下载文件
     *
     * @param url
     * @param path
     * @return: org.springframework.http.ResponseEntity<byte [ ]>
     */
    @Override
    public String download(String url,String path) {
        String pre = ossProperties.getEndpoint()+PATH_SEPARATOR+ossProperties.getBucketName();
        String fileName = url.startsWith(pre)?url.replace(pre,""):url;
        log.info(" download pre is {} ",pre);
        log.info(" download fileName is {} ",fileName);
        InputStream in = null;
        FileOutputStream fos = null;
        try {
            in = minioClient.getObject(GetObjectArgs.builder().bucket(ossProperties.getBucketName()).object(fileName).build());
            String realFIleName = fileName.contains("/")?fileName.substring(fileName.lastIndexOf("/")+1):fileName;
            File file = new File(path);
            if(path.contains(realFIleName)){
                log.info("file  mkdirs");
                File pfile=file.getParentFile();
                if(!pfile.exists()){
                    pfile.mkdirs();
                }
            }else{
                log.info("file isDirectory  mkdirs");
                file.mkdirs();
            }
            log.info(" write file is {} ",path+PATH_SEPARATOR+realFIleName);
            fos = new FileOutputStream(path+PATH_SEPARATOR+realFIleName);
            byte[] b = new byte[1024];
            int length;
            while((length= in.read(b)) > 0){
                fos.write(b,0,length);
            }
            return path+PATH_SEPARATOR+realFIleName;

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (in != null) {
                    try {
                        in.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (fos != null) {
                    fos.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    /**
     * description: 下载文件
     *
     * @param url
     * @return: org.springframework.http.ResponseEntity<byte [ ]>
     */
    @Override
    public InputStream download(String url) {
        try{
            String pre = ossProperties.getEndpoint()+PATH_SEPARATOR+ossProperties.getBucketName();
            String fileName = url.startsWith(pre)?url.replace(pre,""):url;
            return minioClient.getObject(GetObjectArgs.builder().bucket(ossProperties.getBucketName()).object(fileName).build());
        }catch (Exception e){
            log.error("minio下载失败",e);
        }
        return null;
    }


    /**
     *
     * @param url
     * @return
     */
    @Override
    public byte[] downloadByte(String url) {
        try{
            if(StringUtils.containsIgnoreCase(url,"Credential")){
                log.info("downloadByte url is getPreviewUrl {}",url);
                url=StringUtils.substringBeforeLast(url,"?");
            }
            if(!StringUtils.startsWithIgnoreCase(url,"/")){
                url="/"+url;
            }
            //文件检测
//            if(!checkFileIsExist(ossProperties.getBucketName(),url)){
            Assert.isTrue(checkFileIsExist(ossProperties.getBucketName(),url),"下载对象不存在");
//            }
            String pre = ossProperties.getEndpoint()+PATH_SEPARATOR+ossProperties.getBucketName();
            String fileName = url.startsWith(pre)?url.replace(pre,""):url;
            return minioClient.getObject(GetObjectArgs.builder().bucket(ossProperties.getBucketName()).object(fileName).build()).readAllBytes();
        }catch (Exception e){
            log.error("minio下载失败",e);
            throw  new  RuntimeException(e);
        }
    }


    /**
     * description: 下载文件

     * @param url
     * @return: org.springframework.http.ResponseEntity<byte [ ]>
     */
    @Override
    public ResponseEntity<byte[]> downloadByUrl(String url) {
        String pre = ossProperties.getEndpoint()+PATH_SEPARATOR+ossProperties.getBucketName();
        String fileName = url.startsWith(pre)?url.replace(pre,""):url;
        ResponseEntity<byte[]> responseEntity = null;
        InputStream in = null;
        ByteArrayOutputStream out = null;
        try {
            in = minioClient.getObject(GetObjectArgs.builder().bucket(ossProperties.getBucketName()).object(fileName).build());
            out = new ByteArrayOutputStream();
            Writer writer = new OutputStreamWriter(out, StandardCharsets.UTF_8);
            IOUtils.copy(in, writer,StandardCharsets.UTF_8);
            //封装返回值
            byte[] bytes = out.toByteArray();
            HttpHeaders headers = new HttpHeaders();
            try {
                String realFIleName = fileName.contains("/")?fileName.substring(fileName.lastIndexOf("/")+1):fileName;
                headers.add("Content-Disposition", "attachment;filename=" + URLEncoder.encode(realFIleName, "UTF-8"));
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            headers.setContentLength(bytes.length);
            headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
            headers.setAccessControlExposeHeaders(Arrays.asList("*"));
            responseEntity = new ResponseEntity<byte[]>(bytes, headers, HttpStatus.OK);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (in != null) {
                    try {
                        in.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (out != null) {
                    out.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return responseEntity;
    }



    /**
     * 批量删除文件对象
     *
     * @param bucketName 存储bucket名称
     * @param objects    对象名称集合
     */
    @Override
    public Iterable<com.agile4j.oss.adapter.Result<com.agile4j.oss.adapter.DeleteError>> removeObjects(String bucketName, List<String> objects) {
        List<DeleteObject> dos = objects.stream().map(e -> new DeleteObject(e)).collect(Collectors.toList());
        Iterable<Result<DeleteError>> results = minioClient.removeObjects(RemoveObjectsArgs.builder().bucket(bucketName).objects(dos).build());
        Iterable<com.agile4j.oss.adapter.Result<com.agile4j.oss.adapter.DeleteError>> resultIterable=new ArrayList<>();
//        Iterable<com.agile4j.oss.adapter.Result<com.agile4j.oss.adapter.DeleteError>> resultIterable=
        for (Result<DeleteError> result : results) {
            com.agile4j.oss.adapter.DeleteError deleteError=new  com.agile4j.oss.adapter.DeleteError();


            com.agile4j.oss.adapter.Result<com.agile4j.oss.adapter.DeleteError> deleteErrorResult=new  com.agile4j.oss.adapter.Result<com.agile4j.oss.adapter.DeleteError>();
        }

        return resultIterable;
    }




    /**
     * 删除文件对象(单个)
     *
     */
    @Override
    public String delete(String module,String fileName) {
        /**
         * String bucketName = "test2";
         * String fileName = "/2023-04-07/16808560218465670_img.png";
         * address+bucketName+fileName 就是访问路径，删除需要后两个参数。
         */
        String name = PATH_SEPARATOR+module+PATH_SEPARATOR+fileName;
        try {
            if(!checkFileIsExist(ossProperties.getBucketName(),name)){return "该文件不存在";}
            minioClient.removeObject(RemoveObjectArgs.builder().bucket(ossProperties.getBucketName()).object(name).build());
        } catch (Exception e) {
            log.error("删除失败",e);
        }
        log.info("删除成功");
        return ossProperties.getEndpoint()+PATH_SEPARATOR+ossProperties.getBucketName()+name;
    }

    /**
     * 判断文件是否存在
     *
     * @param bucketName 桶名称
     * @param objectName 文件名称, 如果要带文件夹请用 / 分割, 例如 /help/index.html
     * @return true存在, 反之
     */
    @Override
    public Boolean checkFileIsExist(String bucketName, String objectName) {
        try {
            minioClient.statObject(
                    StatObjectArgs.builder().bucket(bucketName).object(objectName).build()
            );
        } catch (Exception e) {
            return false;
        }
        return true;
    }


    /**
     *
     * @param sourcePath 桶内得已存在文件名地址
     * @param copyPath   桶内得copy后的文件名地址
     * @return
     */
    @Override
    public Map<String,Object> copyObject(String sourcePath, String copyPath) throws RuntimeException {
        CopyObjectArgs.Builder builder=CopyObjectArgs.builder();
        String fileName= org.apache.commons.lang3.StringUtils.substringAfterLast(sourcePath,PATH_SEPARATOR);
        GetObjectResponse getObjectResponse=null;
        GetObjectArgs getObjectArgs=GetObjectArgs.builder().bucket(ossProperties.getBucketName()).object(sourcePath).build();
        try {
            getObjectResponse=  minioClient.getObject(getObjectArgs);
        } catch (ErrorResponseException | InsufficientDataException | InternalException | InvalidKeyException |
                 InvalidResponseException | IOException | NoSuchAlgorithmException | XmlParserException |
                 ServerException e) {
            throw new RuntimeException(e);
        }
        ObjectWriteResponse ObjectWriteResponse=null;
        //builder.object(ossProperties.getBucketName());
        CopySource copySource=CopySource.builder()
                .bucket(ossProperties.getBucketName())
                .object(sourcePath)
                .build();
        builder.source(copySource);
        builder.bucket(ossProperties.getBucketName());
        builder.object(copyPath);
        try {
            ObjectWriteResponse=  minioClient.copyObject(builder.build());
        } catch (ErrorResponseException | InternalException | InsufficientDataException | InvalidKeyException |
                 InvalidResponseException | IOException | NoSuchAlgorithmException | ServerException |
                 XmlParserException e) {
            throw new RuntimeException(e);
        }
        Map<String,Object> sysFile = new HashMap<>(16);
        sysFile.put("multipartFileName",fileName);
        sysFile.put("fileType",org.apache.commons.lang3.StringUtils.substringAfterLast(fileName,"."));
        sysFile.put("referFlag",false);
        sysFile.put("fileName",fileName);
        String url=ossProperties.getEndpoint()+PATH_SEPARATOR+ossProperties.getBucketName()+copyPath;
        sysFile.put("url",url);
        sysFile.put("fileUrl",url);
        try {
            sysFile.put("fileSize",getObjectResponse.readAllBytes().length);
            sysFile.put("size",getObjectResponse.readAllBytes().length);
            sysFile.put("mD5", DigestUtils.md5DigestAsHex(getObjectResponse.readAllBytes()));
        } catch (IOException e) {
            log.error(e.getMessage(),e);
            throw new RuntimeException(e);
        }
        return sysFile;
    }


    /**
     * description: 上传文件
     *
     * @param multipartFile
     * @return: java.lang.String
     */
    @Override
    public Map<String,Object> upload(MultipartFile multipartFile, String path) {
        if (!path.endsWith(PATH_SEPARATOR)) {
            path += PATH_SEPARATOR;
        }
        if (!path.startsWith(PATH_SEPARATOR)) {
            path = PATH_SEPARATOR + path;
        }
        String name=multipartFile.getOriginalFilename();
        String fileType = getExtension(multipartFile);
        File file= null;
        try {
            file = File.createTempFile(path+name,fileType);
        } catch (IOException e) {
            log.error(e.getMessage(),e);
            throw new RuntimeException(e);
        }
        try {
            multipartFile.transferTo(Paths.get(file.getPath()));
        } catch (IOException e) {
            log.error(e.getMessage(),e);
            throw new RuntimeException(e);
        }
        log.info("createTempFile file {}",file.getPath());
//		String name = multipartFile.getOriginalFilename();
        String fileName = path + UlidBuilder.getUlid(System.currentTimeMillis()) +'.'+fileType;

        log.info("multipartFile getOriginalFilename {},fileType {} fileName {},", name, fileType, fileName );
        InputStream in = null;
        try {
            in = new FileInputStream(file);
            minioClient.putObject(PutObjectArgs.builder()
                    .bucket(ossProperties.getBucketName())
                    .object(fileName)
                    .stream(new FileInputStream(file), multipartFile.getSize(), -1)
                    .contentType(multipartFile.getContentType())
                    .build()
            );
            Map<String,Object> sysFile = new HashMap<>(16);
            sysFile.put("multipartFileName",name);
            sysFile.put("fileType",fileType);
            sysFile.put("referFlag",false);
            sysFile.put("fileName",fileName);
            String url=null;


            if(!StringUtils.startsWithIgnoreCase(fileName,PATH_SEPARATOR)){
                url=ossProperties.getEndpoint()+PATH_SEPARATOR+ossProperties.getBucketName()+PATH_SEPARATOR+fileName;
            }else{
                url=ossProperties.getEndpoint()+PATH_SEPARATOR+ossProperties.getBucketName()+fileName;
            }
            log.info("oss upload file {}",url);
            sysFile.put("fileUrl",url);
            sysFile.put("url",url);
            sysFile.put("createTime", LocalDateTime.now());
            sysFile.put("fileSize",multipartFile.getSize());
            sysFile.put("size",multipartFile.getSize());
            sysFile.put("MD5",DigestUtils.md5DigestAsHex(in));
            if(isImage(fileType)){
                sysFile.put("previewUrl", url);
            }else{
                sysFile.put("previewUrl", getPreviewUrl(url));
            }
//            sysFile.put("previewUrl", getPreviewUrl(url));

//			sysFile.setFileType(ossProperties.getEndpoint()+PATH_SEPARATOR+ossProperties.getBucketName()+fileName);
//			sysFile.setReferFlag(false);
//			sysFile.setUrl(minioUrl+PATH_SEPARATOR+bucketName+fileName);
//			sysFile.setCreateTime(LocalDateTime.now());
//			sysFile.setSize(multipartFile.getSize());
//			sysFile.setMD5(DigestUtils.md5DigestAsHex(in));
            return sysFile;
        } catch (Exception e) {
            log.error(e.getMessage(),e);
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    log.error(e.getMessage(),e);
                }
            }
        }

        return null;
    }

    /**
     *  description: 上传文件
     * @param inputStream
     * @param path
     * @param fileName
     * @return
     */
    @Override
    public Map<String,Object> upload(FileInputStream inputStream, String path,String fileName) {
        if (!path.endsWith(PATH_SEPARATOR)) {
            path += PATH_SEPARATOR;
        }
        if (!path.startsWith(PATH_SEPARATOR)) {
            path = PATH_SEPARATOR + path;
        }
        String fileType = getExtension(fileName);
        String name = StringUtils.substringBeforeLast(fileName,".");
        String newFileName = path + UlidBuilder.getUlid(System.currentTimeMillis()) +'.'+fileType;
        log.info("multipartFile getOriginalFilename {},fileType {} fileName {},", name, fileType, newFileName );
        try {

            FileChannel channel = inputStream.getChannel();
            // ✅ 通过 Channel 获取大小
            long size = channel.size();

            minioClient.putObject(PutObjectArgs.builder()
                    .bucket(ossProperties.getBucketName())
                    .object(newFileName)
                    .stream(inputStream, size, -1)
                    .contentType(fileType)
                    .build()
            );
            Map<String,Object> sysFile = new HashMap<>(16);
            sysFile.put("multipartFileName",name);
            sysFile.put("fileType",fileType);
            sysFile.put("referFlag",false);
            sysFile.put("fileName",newFileName);
            String url=null;
            if(!StringUtils.startsWithIgnoreCase(newFileName,PATH_SEPARATOR)){
                url=ossProperties.getEndpoint()+PATH_SEPARATOR+ossProperties.getBucketName()+PATH_SEPARATOR+newFileName;
            }else{
                url=ossProperties.getEndpoint()+PATH_SEPARATOR+ossProperties.getBucketName()+newFileName;
            }
            log.info("oss upload file {}",url);
            sysFile.put("fileUrl",url);
            sysFile.put("url",url);
            sysFile.put("createTime",LocalDateTime.now());
            sysFile.put("fileSize",size);
            sysFile.put("size",size);
            sysFile.put("MD5",DigestUtils.md5DigestAsHex(inputStream));
            if(isImage(fileType)){
                sysFile.put("previewUrl", url);
            }else{
                sysFile.put("previewUrl", getPreviewUrl(url));
            }
//            sysFile.put("previewUrl", getPreviewUrl(url));

//			sysFile.setFileType(ossProperties.getEndpoint()+PATH_SEPARATOR+ossProperties.getBucketName()+fileName);
//			sysFile.setReferFlag(false);
//			sysFile.setUrl(minioUrl+PATH_SEPARATOR+bucketName+fileName);
//			sysFile.setCreateTime(LocalDateTime.now());
//			sysFile.setSize(multipartFile.getSize());
//			sysFile.setMD5(DigestUtils.md5DigestAsHex(in));
            return sysFile;
        } catch (Exception e) {
            log.error(e.getMessage(),e);
        } finally {
            log.info("oss upload file {}",newFileName);
        }

        return null;
    }

    public static final String getExtension(@NotNull MultipartFile file)
    {
        String extension = FilenameUtils.getExtension(file.getOriginalFilename());
        if (StringUtils.isEmpty(extension))
        {
            extension = getExtension(Objects.requireNonNull(file.getContentType()));
        }
        return extension;
    }


    private static final Pattern IMAGE_PATTERN =
            Pattern.compile("\\.(jpg|jpeg|png|gif|webp|bmp|tiff|tif|svg|ico)$", Pattern.CASE_INSENSITIVE);

    public static boolean isImage(String filename) {
        return IMAGE_PATTERN.matcher(filename).find();
    }

    public static final String IMAGE_PNG = "image/png";

    public static final String IMAGE_JPG = "image/jpg";

    public static final String IMAGE_JPEG = "image/jpeg";

    public static final String IMAGE_BMP = "image/bmp";

    public static final String IMAGE_GIF = "image/gif";


    public static String getExtension(String prefix)
    {
        switch (prefix)
        {
            case IMAGE_PNG:
                return "png";
            case IMAGE_JPG:
                return "jpg";
            case IMAGE_JPEG:
                return "jpeg";
            case IMAGE_BMP:
                return "bmp";
            case IMAGE_GIF:
                return "gif";
            default:
                return "";
        }
    }

    @Override
    public Map<String,Object> uploadRel(MultipartFile multipartFile, String path) {
        InputStream in = null;
        try {
            if (!path.endsWith(PATH_SEPARATOR)) {
                path += PATH_SEPARATOR;
            }
            if (!path.startsWith(PATH_SEPARATOR)) {
                path = PATH_SEPARATOR + path;
            }
//			String name = multipartFile.getOriginalFilename();
//			String fileType = name.substring(name.indexOf(".")+1);
            //String fileName = path + UlidBuilder.getUlid(System.currentTimeMillis()) +'.'+fileType;

            String name = multipartFile.getOriginalFilename();
            String fileType = StringUtils.substringAfterLast(name,".");
//			String fileName = path + UlidBuilder.getUlid(System.currentTimeMillis()) +'.'+fileType;
            String fileName =path+name;
            if(!fileName.contains(fileType)){
                fileName=fileName+fileType;
            }
            log.info("putObject fileName{}, {}",fileName,multipartFile.getContentType());
            in = multipartFile.getInputStream();
            minioClient.putObject(PutObjectArgs.builder()
                    .bucket(ossProperties.getBucketName())
                    .object(fileName)
                    .stream(multipartFile.getInputStream(), multipartFile.getSize(), -1)
                    .contentType(multipartFile.getContentType())
                    .build()
            );
            Map<String,Object> sysFile = new HashMap<>(16);
            sysFile.put("multipartFileName",name);
            sysFile.put("fileType",fileType);
            sysFile.put("referFlag",false);
            sysFile.put("fileName",fileName);
            String url=null;
            if(!StringUtils.startsWithIgnoreCase(fileName,PATH_SEPARATOR)){
                url=ossProperties.getEndpoint()+PATH_SEPARATOR+ossProperties.getBucketName()+PATH_SEPARATOR+fileName;
            }else{
                url=ossProperties.getEndpoint()+PATH_SEPARATOR+ossProperties.getBucketName()+fileName;
            }
            sysFile.put("fileUrl",url);
            sysFile.put("url",url);
            sysFile.put("createTime",LocalDateTime.now());
            sysFile.put("fileSize",multipartFile.getSize());
            sysFile.put("size",multipartFile.getSize());
            sysFile.put("MD5",DigestUtils.md5DigestAsHex(in));
            if(isImage(fileType)){
                sysFile.put("previewUrl", url);
            }else{
                sysFile.put("previewUrl", getPreviewUrl(url));
            }
            //			sysFile.setFileType(ossProperties.getEndpoint()+PATH_SEPARATOR+ossProperties.getBucketName()+fileName);
            //			sysFile.setReferFlag(false);
            //			sysFile.setUrl(minioUrl+PATH_SEPARATOR+bucketName+fileName);
            //			sysFile.setCreateTime(LocalDateTime.now());
            //			sysFile.setSize(multipartFile.getSize());
            //			sysFile.setMD5(DigestUtils.md5DigestAsHex(in));
            return sysFile;
        } catch (Exception e) {
            log.info(e.getMessage(),e);
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    log.info(e.getMessage(),e);
                }
            }
        }

        return null;
    }



    /**
     * 查看文件对象
     *
     * @param bucketName 存储bucket名称
     * @return 存储bucket内文件对象信息
     */
    @Override
    public List<Map<String,Object>> listObjects(String bucketName) {
        Iterable<Result<Item>> results = minioClient.listObjects(
                ListObjectsArgs.builder().bucket(bucketName).build());
        List<Map<String,Object>> objectItems = new ArrayList<>();
        try {
            for (Result<Item> result : results) {
                Item item = result.get();
                Map<String,Object> objectItem = new HashMap<>(16);
                objectItem.put("fileName",item.objectName());
                objectItem.put("size",item.size());
//				objectItem.setFileName(item.objectName());
//				objectItem.setSize(item.size());
                objectItems.add(objectItem);
            }
        } catch (Exception e) {
            log.info(e.getMessage(),e);
            return null;
        }
        return objectItems;
    }




    public MultipartFile toMultipartFile(@NotNull File file) {
        try {
            Path path = Paths.get(file.getAbsolutePath());
            String name = file.getName();
            String originalFileName = file.getName();
            String contentType = Files.probeContentType(path);
            byte[] content = null;
            try {
                content = Files.readAllBytes(path);
            } catch (final IOException e) {
                log.error(e.getMessage(),e);
            }
            return new MockMultipartFile(name,
                    originalFileName, contentType, content);
        } catch (IOException e) {
            log.info(e.getMessage(),e);
            return null;
        }
    }


    @Override
    public String getPreviewUrl(String pathUrl) {
        /* 获取文件名称 */
        String fileName  = StringUtils.substringAfterLast(pathUrl,"/");
        /* 获取桶后面的下载路径 */
        String downUrl = StringUtils.substringAfterLast(pathUrl,ossProperties.getBucketName());
        /* 获取预览的路径 */
        String url = null;
        log.info("fileName is {},downUrl is {} ",fileName,downUrl);
        try {
            if(StringUtils.startsWithIgnoreCase(downUrl,"/")){
                downUrl= StringUtils.substring(downUrl, 1,StringUtils.length(downUrl));
            }

            url = minioClient.getPresignedObjectUrl(GetPresignedObjectUrlArgs.builder()
                    .method(Method.GET)
                    .bucket(ossProperties.getBucketName())
                    .object(downUrl)
//                    .expiry(360000, TimeUnit.DAYS)
                    .build());
        } catch (ErrorResponseException | InsufficientDataException | InternalException | InvalidKeyException |
                 IOException | InvalidResponseException | NoSuchAlgorithmException | XmlParserException |
                 ServerException e) {
            log.info("getPresignedObjectUrl error, url:{} {}",downUrl ,fileName);
            throw new RuntimeException(e);
        }
        log.info("fileName is {},downUrl is {} file path {} previewUrl {}",fileName,downUrl,pathUrl, url);
        return url;
    }

    @Override
    public List<String> getBucketObjects(String bucketName) {
        return List.of();
    }

    @Override
    public void removeObject(String module, String fileName) {

    }

    @Override
    public void createBucket(String bucketName) {

    }

    @Override
    public void putObject(String module, String path, String filePath) {

    }
}